package org.zoomdev.zoom.event.modules;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.aop.AopFactory;
import org.zoomdev.zoom.aop.annotations.NoEnhance;
import org.zoomdev.zoom.async.AsyncService;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.common.res.ResScanner;
import org.zoomdev.zoom.event.EventService;
import org.zoomdev.zoom.ioc.annotations.Inject;
import org.zoomdev.zoom.ioc.annotations.IocBean;
import org.zoomdev.zoom.ioc.annotations.Module;
import org.zoomdev.zoom.ioc.annotations.ModuleInit;

import java.util.List;

@NoEnhance
@Module
public class CoreEventModule {

    public static final String NAME = "EVENT_MODULE";
    /**
     * 启动日志
     */
    public static boolean enableLog = true;
    /**
     * 自动扫描
     */
    public static boolean autoScan = true;
    private final Logger log = LoggerFactory.getLogger(CoreEventModule.NAME);
    @Inject(config = "zoom.scan.eventListeners")
    private String searchPath;

    @IocBean
    public EventService getEventService() {
        return new EventServiceImpl();
    }

    @ModuleInit
    public void config(AopFactory aopFactory, EventService eventService, AsyncService asyncService) {
        aopFactory.addFactory(new EventNotifierInterceptorFactory(eventService, asyncService), 0);
    }

    @ModuleInit()
    public void init(ResScanner scanner, EventObserverInterceptorFactory factory) {
        if (!autoScan) {
            return;
        }
        log.info(">>> Auto scan event listeners");
        if (StringUtils.isEmpty(searchPath)) {
            searchPath = "!java*&!sun*&(*.services.*|*Service|*.Job|*.Model)";
        }

        List<ResScanner.ClassRes> classes = scanner.findClass(searchPath);
        for (ResScanner.ClassRes res : classes) {
            try {
                Class<?> modelClass = res.getType();
                if (modelClass.isInterface()) {
                    //先不处理 interface
                    continue;
                }

                factory.register(modelClass);
            } catch (Throwable e) {
                log.warn("解析发生异常", e);
                throw new ZoomException(e);
            }

        }
    }
}
